﻿using System.Net;
using System.Web.Security;
using System.DirectoryServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Marbles.Data.LDAP
{
    internal class LDAPCommunicationLayer
    {

        private string RootAddress = string.Empty;
        private NetworkCredential Credentials = null;

        public LDAPCommunicationLayer(string Server, string Username, string Password, string Domain)
        {
            this.RootAddress = string.Format("LDAP://{0}/CN=Users,DC={1},DC=ukthontd01ad,DC=timbmet,DC=com", Server);
            this.Credentials = new NetworkCredential(Username, Password, Credentials.Domain);
        }

        public LDAPCommunicationLayer(string Server, NetworkCredential Credentials)
        {
            if (Credentials.Domain != string.Empty)
            {
                this.RootAddress = string.Format("LDAP://{0}/CN=Users,DC=ukthontd01ad,DC=timbmet,DC=com", Server);
                this.Credentials = new NetworkCredential(Credentials.UserName, Credentials.Password, Credentials.Domain);
            }
            else
            {
                this.RootAddress = string.Format("LDAP://{0}/CN=Users", Server);
                this.Credentials = new NetworkCredential(Credentials.UserName, Credentials.Password);
            }
        }

        private DirectoryEntry GetLdapRoot(AuthenticationTypes AuthenticationType)
        {
            return new DirectoryEntry(this.RootAddress, GetLdapUsername(), this.Credentials.Password, AuthenticationType);
        }

        private string GetLdapUsername()
        {
            if (this.Credentials.Domain != string.Empty)
            {
                return string.Format("{0}\\{1}", this.Credentials.Domain, this.Credentials.UserName);
            }

            return this.Credentials.UserName;
        }


        private object GetProperty(string key, ResultPropertyCollection Result)
        {
            foreach (string s in Result.PropertyNames)
            {
                if (s.ToLower() == key.ToLower())
                {
                    ResultPropertyValueCollection value = Result[s];
                    if (value.Count > 0)
                    {
                        if (value[0] != null) { return value[0]; }
                        return null;
                    }
                }
            }

            return null;
        }

        private string GetProperty(string key, PropertyCollection Result)
        {
            foreach (string s in Result.PropertyNames)
            {
                if (s.ToLower() == key.ToLower())
                {                    
                    PropertyValueCollection value = Result[s];
                    if (value.Count > 0)
                    {
                        if (value[0] != null) { return value[0].ToString(); }
                        return string.Empty;
                    }
                }
            }

            return string.Empty;
        }

        public LDAPUser GetUserByAccountName(string sAMAccountName)
        {
            string Address = GetUserAddressByAccountName(sAMAccountName);
            if (Address == string.Empty) { return null; }
            return GetUserbyAddress(Address);
        }

        public LDAPUser GetUserbyAddress(string AdsPath)
        {
            LDAPUser user = null;
            DirectoryEntry entry = new DirectoryEntry(AdsPath, GetLdapUsername(), this.Credentials.Password, AuthenticationTypes.ReadonlyServer);

            if (entry != null)
            {
                user = new LDAPUser(entry.Properties, entry.Guid);
                entry.Close();
                entry.Dispose();
            }

            return user;
        }

        public static bool Authenticate(string userName, string password, string domain)
        {
            bool authentic = false;
            try
            {
                DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password);
                object nativeObject = entry.NativeObject;
                authentic = true;
            }
            catch (DirectoryServicesCOMException) { }
            return authentic;
        }

        public string GetUserAddressByAccountName(string sAMAccountName)
        {
            DirectoryEntry root = GetLdapRoot(AuthenticationTypes.ReadonlyServer);
            DirectorySearcher finder = new DirectorySearcher(root);
            SearchResult result = null;
            string address = string.Empty;
            finder.Filter = string.Format("(sAMAccountName={0})", sAMAccountName);
            finder.ClientTimeout = new TimeSpan(0, 0, 5);
            finder.CacheResults = true;
            result = finder.FindOne();

            if (result != null)
            {
                object value = GetProperty("adspath", result.Properties);
                if (value != null) { address = value.ToString(); }
            }

            finder.Dispose();
            root.Close();
            root.Dispose();
            return address;
        }

        public bool IsMemberofObjectClass(string sAMAccountName, string ObjectClass)
        {
            LDAPUser user = GetUserByAccountName(sAMAccountName);

            foreach (string s in user.ObjectClass)
            {
                if (s.ToLower() == ObjectClass.ToLower()) { return true; }
            }

            return false;        
        }

        public bool IsMemberofObjectClass(string sAMAccountName, ObjectClass ObjectClass)
        {
            LDAPUser user = GetUserByAccountName(sAMAccountName);

            foreach (string s in user.ObjectClass)
            {
                if (s.ToLower() == ObjectClass.ToString().ToLower()) { return true; }
            }

            return false;
        }

    }
}
